package com.dididoctor.patient.Activity.Consult;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dididoctor.patient.Activity.Inquiry.InquiryActivity;
import com.dididoctor.patient.Activity.Message.SystemMessage.SystemMessage;
import com.dididoctor.patient.Activity.Message.SystemMessage.SystemMessageAdapter;
import com.dididoctor.patient.Activity.Service.ServiceDetail.ServiceDetailActivity;
import com.dididoctor.patient.Bean.DiaeasesLitapal;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.Dialog.DiseaseListDialog;
import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.customlistview.OnRefreshListener;
import com.dididoctor.patient.Ui.customlistview.RefreshListView;
import com.dididoctor.patient.Utils.LoaderImage;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.Utils.UserHeadImage;
import com.dididoctor.patient.WYY.SessionHelper;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.loopj.android.image.SmartImageView;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： ConsultActivity
 * @包名称： com.dididoctor.doctor.Activity.Trends
 * @创建人： zhanjunjie
 * @创建时间：2016/4/1 15:19
 * @修改人：
 * @修改时间：2016/4/1 15:19
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class ConsultActivity extends EduActivity implements ConsultView {


    //控件
    private RelativeLayout mRlTop, mRelActivity;
    private LinearLayout mLlBottom, mLlDefeated, mLlImgOrText, mLlCall, mLlPayZhifubao;
    private Button mBtSige;
    private TextView mTvName, mTvJob, mTVSige, mTvAddress;
    private UserHeadImage headImage;
    private LoaderImage loaderImage;

    private ConsultPresenter presenter;
    private String hosid = "", doctorid = "", price = "", hosId = "";
    private List<DiaeasesLitapal> litapals = new ArrayList<>();
    private String phone;
    private String accId;
    private String name;
    private RefreshListView listView;
    private SystemMessageAdapter adapter;
    private List<SystemMessage> messages = new ArrayList<>();
    private ImageView mImgDelete;
    private SmartImageView mImgDetail;
    private int pageIndex = 1;

    @Override
    public void init() {
        //初始化控件
        initview();

        initdata();
    }

    private void initdata() {


        presenter = new ConsultPresenter(this, this);
        presenter.getdoctorInfo();
    }

    private void initview() {
        mRlTop = (RelativeLayout) findViewById(R.id.rel_top);
        mLlBottom = (LinearLayout) findViewById(R.id.lin_bottom);
        mLlDefeated = (LinearLayout) findViewById(R.id.ll_rob_defeated);
        mBtSige = (Button) findViewById(R.id.btn_fail_ok);
        mBtSige.setOnClickListener(this);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mTvJob = (TextView) findViewById(R.id.tv_job);
        mTVSige = (TextView) findViewById(R.id.tv_sigeorpin);
        mTvAddress = (TextView) findViewById(R.id.tv_address);
        mLlImgOrText = (LinearLayout) findViewById(R.id.lin_imgortext);
        mLlCall = (LinearLayout) findViewById(R.id.lin_call_counsel);
        headImage = (UserHeadImage) findViewById(R.id.img_user);
        loaderImage = new LoaderImage(this);

        mRelActivity = (RelativeLayout) findViewById(R.id.rel_activity);
        mImgDetail = (SmartImageView) findViewById(R.id.img_detail);
        mImgDetail.setOnClickListener(this);
        mImgDelete = (ImageView) findViewById(R.id.img_delete);
        mImgDelete.setOnClickListener(this);

        findViewById(R.id.lin_call_counsel).setOnClickListener(this);
        findViewById(R.id.lin_imgortext).setOnClickListener(this);
        //24z中小病
        litapals = DiaeasesLitapal.getdisarases();
        listView = (RefreshListView) findViewById(R.id.listview);
        adapter = new SystemMessageAdapter(this, messages);
        listView.setAdapter(adapter);
        listView.setHeadAndFoot(true, true);
        listView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                pageIndex = 1;
                presenter.getmessageInfo(pageIndex);
                listView.onRefreshFinish();
            }

            @Override
            public void onLoadMoring() {
                pageIndex++;
                presenter.getmessageInfo(pageIndex);
                listView.onRefreshFinish();
            }

            @Override
            public void onScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        if ("1".equals(SharedPreferencesUtils.getParam(ConsultActivity.this, "event_isShow", "0"))) {
            mRelActivity.setVisibility(View.VISIBLE);
            mImgDetail.setImageUrl(SharedPreferencesUtils.getParam(ConsultActivity.this, "event_picUrl", "0"));
        }
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_fail_ok: {
                Intent intent = new Intent("MyReceiver");
                sendBroadcast(intent);
            }
            break;
            case R.id.lin_call_counsel: {

                DiseaseListDialog diseaseListDialog = new DiseaseListDialog(this, litapals, new DiseaseListDialog.onItemClickListener() {
                    @Override
                    public void itemClick(int position) {
                        DiaeasesLitapal litapal = litapals.get(position);
                        String disname = litapal.getName();
                        String disid = litapal.getDisId();
//                        userId	String	是	用户id
//                        token	String	是	唯一标示
//                        reqType	String	是	1-医生拨打患者电话 2-患者拨打医生电话
//                        accId	String	是	云信id
//                        caller	String	是	主叫电话号码
//                        callee	String	是	被叫电话号码
//                        hosId	String	否	医生医院id reqType=2时用
//                        doctorId	String	否	医生id reqType=2时用
//                        diseId	String	否	病种id reqType=2时用
//                        recId	String	否	病历id reqType=1时用

                        presenter.getCalling(phone, hosId, doctorid, "", disid);
                    }

                    @Override
                    public void setfinis() {

                    }
                });
                diseaseListDialog.show();
//                Intent intent = new Intent(this, MakeCallActivity.class);
//                intent.putExtra("hosid", hosid);
//                intent.putExtra("doctorid", doctorid);
//                intent.putExtra("price", price);
//                startActivity(intent);

            }
            break;
            case R.id.lin_imgortext:
                presenter.getgoAndFrom(hosid);
                break;
            case R.id.img_delete:
                mRelActivity.setVisibility(View.GONE);
                break;
            case R.id.img_detail:
                Intent intent = new Intent(this, ServiceDetailActivity.class);
                intent.putExtra("webUrl", SharedPreferencesUtils.getParam(ConsultActivity.this, "event_webUrl", "0"));
                startActivity(intent);
                SharedPreferencesUtils.setParam(ConsultActivity.this, "event_isShow", "0");
                mRelActivity.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 根据用户生日计算年龄
     */
    public static int getAgeByBirthday(Date birthday) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_consult);
    }

    @Override
    public void getdoctorsucced(Consult consult) {
        hosid = consult.getHospitalId();
        accId = consult.getAccId();
        phone = consult.getPhone();
        doctorid = consult.getDoctorId();
        SharedPreferencesUtils.setParam(ConsultActivity.this, "isSignDoctorid", doctorid);
        hosId = consult.getHospitalId();
        price = consult.getPrice();
        name = consult.getName();
        mTvName.setText(consult.getName());
        mTvJob.setText(consult.getPosition());
        mTVSige.setText("签约数：" + consult.getSignNum() + "       " + "好评率：" + consult.getEvaluate() + "%");
        mTvAddress.setText(consult.getHospital());
        loaderImage.load(headImage, consult.getHeadPic(), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {
                headImage.setImageResource(R.drawable.img_doctordefault);
            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                headImage.setImageResource(R.drawable.img_doctordefault);
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {

            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });

        mLlBottom.setVisibility(View.VISIBLE);
        mRlTop.setVisibility(View.VISIBLE);
        mLlDefeated.setVisibility(View.GONE);
        presenter.getmessageInfo(pageIndex);
    }

    @Override
    public void getdoctorfail() {
        showToastMessage("加载失败");
        mLlBottom.setVisibility(View.GONE);
        mRlTop.setVisibility(View.GONE);
        mLlDefeated.setVisibility(View.VISIBLE);
    }

    @Override
    public void getdoctorno() {
        mLlBottom.setVisibility(View.GONE);
        mRlTop.setVisibility(View.GONE);
        mLlDefeated.setVisibility(View.VISIBLE);
    }

    @Override
    public void IntentInquiryActivity(final String isCmp) {
        DiseaseListDialog diseaseListDialog = new DiseaseListDialog(this, litapals, new DiseaseListDialog.onItemClickListener() {
            @Override
            public void itemClick(int position) {
                DiaeasesLitapal litapal = litapals.get(position);
                String disname = litapal.getName();
                String disid = litapal.getDisId();
                Intent intent = new Intent(ConsultActivity.this, InquiryActivity.class);
                intent.putExtra("disname", disname);
                intent.putExtra("disid", disid);
                intent.putExtra("doctorId", doctorid);
                intent.putExtra("hosId", hosId);
                intent.putExtra("isCmp", isCmp);
                intent.putExtra("accId", accId);
                intent.putExtra("sign", "1");
                intent.putExtra("name", name);
                startActivity(intent);
            }

            @Override
            public void setfinis() {

            }
        });
        diseaseListDialog.show();
    }

    @Override
    public void IntentP2PActivity(String recId, String status) {
        //Todo hosId医生医院id和recId问诊表id   //doctorid医院的ID    accId聊天人的云信ID
        SessionHelper.startP2PSession(this, accId, status, recId, hosId, Token.getId(), Token.getToken(), doctorid, accId, name, "1");
    }

    @Override
    public void IntentP2PActivityGo() {

    }

    @Override
    public void IntentP2PActivityTwo() {

    }

    @Override
    public void getmessage(List<SystemMessage> messages) {
        if (pageIndex == 1) {
            adapter.setData(messages);
        } else {
            adapter.addData(messages);
        }

    }

    @Override
    public void getmessagefail() {
        showToastMessage("请求失败，请检查网络");
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getdoctorInfo();
    }
}
